package com.rimi.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author chengliang
 * 创建时间 2020/3/25 11:31
 * 这是文件下载处理的Servlet
 */
@WebServlet("/down")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //接收需要下载的文件名称
        String fileName = request.getParameter("name");
        //设置下载文件的名称
        String name = "中文.sql";
        //处理中文名称，浏览器无法识别的问题
        byte[] nameBytes = name.getBytes("utf-8");
        String newName = new String(nameBytes, "ISO-8859-1");
        response.setHeader("content-disposition", "attachment;filename=" + newName);
        //到文件保存路径获取文件的输入流信息
        String path = request.getServletContext().getRealPath("/upload/");
        File file = new File(path,fileName);
        if(!file.exists()){
            response.sendRedirect("/index.jsp");
            return;
        }
        //拿到文件的流信息
        InputStream inputStream = new FileInputStream(file);
        //通过响应对象的输出流对象
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024*10];
        while(inputStream.read(bytes) != -1){
            outputStream.write(bytes);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();

        response.getWriter().append("文件上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
